﻿namespace NMortgage.UI.Converters
{
    using System.Globalization;
    using System.Resources;
    using System.Windows;
    using System.Windows.Data;
    using System;

    /// <summary>
    /// Retreives the value from a <code>ResourceManager</code> based on a Name convention of a FrameworkElement $(x:Name)+"_Image"
    /// </summary>
    public class XNameToImageResourceConverter : IValueConverter
    {
        #region Methods

        public object Convert(object value, Type type, object parameter, CultureInfo culture)
        {
            var resourceManager = parameter as ResourceManager;
            var element = value as FrameworkElement;

            if (!ReferenceEquals(element, null) && !ReferenceEquals(resourceManager, null))
            {
                return GetByConvention(resourceManager, element.Name, culture);
            }

            return null;
        }

        public object ConvertBack(object value, Type type, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue; // not supported
        }

        private static object GetByConvention(ResourceManager resourceManager, object name, CultureInfo culture)
        {
            var key = name + "_Image";
            var resourceValue = resourceManager.GetObject(key, culture);
            return resourceValue;
        }

        #endregion Methods
    }
}